<?php

namespace App\CommandModel;
use App\Model\UserCoupon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

//超时未支付订单回库
class OrderSkuReturn
{
    public function run()
    {
        $orders = $this->getOvertimeOrders();

        if ($orders->count() >0 ) {

            //关闭订单
            $ids = $orders->pluck('id')->toArray();
            $res['order'] = $this->closeOrders($ids);

            //优惠券回库
            $this->couponSkuReturn($ids);

            //商品回库
            $sku= $orders->groupBy('product_id')->map(function ($item){
                return $item->sum('quantity');
            });
            $res['product'] = $this->skuReturn($sku);

            return $res;
        }
        return false;
    }

    //获取超时未支付订单
    private function getOvertimeOrders()
    {
        //过期时间
        $time = Config::get('order.order_overtime');

        return DB::table('orders')->where('state','=',0)
            ->where('created_at','<',date('Y-m-d',time() - $time))
            ->where('is_pay','no')
            ->select('id','product_id','quantity')
            ->get();
    }

    //关闭订单(状态由0=>7)
    private function closeOrders($ids)
    {
        return DB::table('orders')->whereIn('id',$ids)->update(['state'=>7]);
    }

    //商品回库
    private function skuReturn($sku)
    {
        $res = [];
        foreach ($sku as $k=>$v){
            $res[] = DB::select('update `wine_product` set sku=sku+' .$v.' where id='.$k);
        }
        return count($res);
    }

    //优惠券回库
    private function couponSkuReturn($ids)
    {
        return UserCoupon::updateWhenOrderCancelByIds($ids);
    }
}
